package main

/*
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>

int get_ipaddr(char * ifname, char * ip)
{
    char *temp = NULL;
    int inet_sock;
    struct ifreq ifr;

    inet_sock = socket(AF_INET, SOCK_DGRAM, 0);

    memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
    memcpy(ifr.ifr_name, ifname, strlen(ifname));

    if(0 != ioctl(inet_sock, SIOCGIFADDR, &ifr))
    {
        perror("ioctl error");
        return -1;
    }

    temp = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);
    memcpy(ip, temp, strlen(temp));

    close(inet_sock);

    return 0;
}
*/
import "C"

import (
	"fmt"
	"log"
	"os"
	"unsafe"
)

func main() {
	if len(os.Args) != 2 {
		log.Fatalf("Usage: %s <interface>\n", os.Args[0])
	}

	ipaddr0 := make([]byte, 32)
	buf0 := (*C.char)(unsafe.Pointer(&ipaddr0[0]))
	argv1 := (*C.char)(unsafe.Pointer(&([]byte(os.Args[1]))[0]))
	C.get_ipaddr(argv1, buf0)

	fmt.Printf("%s: %s\n", os.Args[1], ipaddr0)

	var buf1 [32]C.char
	arg1 := C.CString(os.Args[1])
	defer C.free(unsafe.Pointer(arg1)) //arg1是符合C char*的指针,注意这里释放的是经过unsafe.Pointer()处理过的argv1,也就是转成void *
	C.get_ipaddr(arg1, &buf1[0])

	ipaddr1 := C.GoString(&buf1[0])

	fmt.Printf("%s: %s\n", os.Args[1], ipaddr1)
}
